package com.ciwong.epaper.modules.interactivetutorial;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.PermissionChecker;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.ciwong.ciwongwrite.JournalActivity;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.common.CheckIsExamForDetail;
import com.ciwong.epaper.modules.cordva.SubmitEvent;
import com.ciwong.epaper.modules.epaper.bean.Answer;
import com.ciwong.epaper.modules.epaper.bean.CatalogueInfo;
import com.ciwong.epaper.modules.epaper.bean.H5AnswersResponse;
import com.ciwong.epaper.modules.epaper.bean.Module;
import com.ciwong.epaper.modules.epaper.bean.ModuleContent;
import com.ciwong.epaper.modules.epaper.bean.ModuleInfo;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.ui.NewBookDetailH5Activity;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.epaper.util.ListenSpeakUtil;
import com.ciwong.epaper.modules.epaper.util.RepeatKeyUtil;
import com.ciwong.epaper.modules.evaluate.bean.SentencesDetail;
import com.ciwong.epaper.modules.evaluate.ui.SpeechPlayController;
import com.ciwong.epaper.modules.me.bean.Clazz;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.onlineanswer.OnlineAnswerPhotoBean;
import com.ciwong.epaper.modules.onlineanswer.OnlineAnswerSubMitResultBean;
import com.ciwong.epaper.modules.viedoexplantion.util.ViedoJumpManager;
import com.ciwong.epaper.ui.NewLoginActivity;
import com.ciwong.epaper.util.ALiYunManager;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DeviceUtil;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FeedbackUtil;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.utils.GsonUtil;
import com.ciwong.epaper.widget.NewLoginDialog;
import com.ciwong.eventbus.EventBus;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseRequestUtil;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.utils.XXPermissionTool;
import com.ciwong.mobilelib.widget.CWDialog;
import com.google.gson.Gson;
import com.ciwong.mobilelib.utils.fileprovider.FileProvider7;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.ConfigXmlParser;
import org.apache.cordova.CordovaInterfaceImpl;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewImpl;
import org.apache.cordova.engine.SystemWebChromeClient;
import org.apache.cordova.engine.SystemWebView;
import org.apache.cordova.engine.SystemWebViewClient;
import org.apache.cordova.engine.SystemWebViewEngine;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * 互动教程
 * Created by yyf on 2017/6/7.
 */

public class InteractiveTutorialCordovaActivity extends BaseActivity implements SystemWebViewClient.LoadCallback, View.OnClickListener {
    private Context mContext = this;
    /**
     * 唯一标识符
     */
//    private static final String TEMP_CAMERA_FILE = ESystem.getImagesPath(InteractiveTutorialCordovaActivity.this) + File.separator + "temp.jpg";
    private static final int REQUEST_PERMISSION_CAMERA = 1;
    private String callbackId;
    private String answerJson;
    private int contentId;
    private String mJsonResPath;
    private ModuleContent moduleContent;
    /**
     * 1:作业进来，2：书桌进来
     */
    private int OnlineAnswerFrom = -1;
    public static final int FROM_HOME_WORK = 1;
    public static final int FROM_DESK = 2;
    /**
     * 网页展示内容
     */
    private String result;

    private DownLoadInfo mDownLoadInfo;
    private Module mModule;

    private int position;
    private String classId;
    private String workId = "0";
    protected int mServiceId;
    private UserInfoBase userInfo;
    private Answer tempAnswer;
    private Gson gson = new Gson();
    private long startTime;
    private long returnWorkTime;

    //做题记录
    protected String mUuid = UUID.randomUUID().toString();
    private H5AnswersResponse h5AnswersResponse;
    private String doWorkId;
    private BroadcastReceiver mBroadcastReceiver;


    @Override
    protected void onStart() {
        isjumpToResult = true;
        super.onStart();
    }

    @Override
    protected int setView() {
        return R.layout.activity_online_answer_cordova;
    }

    protected SystemWebView systemWebView;
    protected CordovaWebView cordovaWebView;
    /**
     * 提交中的界面
     */
    LinearLayout ll_submiting;
    RelativeLayout rel_submit_fail;
    Button btn_submit_again;

    @Override
    protected void findViews() {

        ll_submiting = (LinearLayout) findViewById(R.id.ll_submiting);
        systemWebView = (SystemWebView) findViewById(R.id.system_webview);
        systemWebView.getSettings().setBuiltInZoomControls(false);
        systemWebView.getSettings().setSavePassword(false);
        //android 11 上面google出于安全考虑，不推荐用webview直接访问文件，如果实际项目中有需要，就需要设置为true
        systemWebView.getSettings().setAllowFileAccess(true);
        btn_submit_again = (Button) findViewById(R.id.btn_submit_again);
        rel_submit_fail = (RelativeLayout) findViewById(R.id.rel_submit_fail);
    }

    @Override
    protected void init() {
        Intent intent = getIntent();

        TAG = "InteractiveTutorialCordovaActivity";

        CWLog.e(TAG, "InteractiveTutorialCordovaActivity onCreate");

        SystemWebViewEngine systemWebViewEngine = new SystemWebViewEngine(systemWebView);
        cordovaWebView = new CordovaWebViewImpl(systemWebViewEngine);
        ConfigXmlParser configXmlParser = new ConfigXmlParser();
        configXmlParser.parse(this);
        cordovaWebView.init(this, cordovaInterface, configXmlParser.getPluginEntries(), configXmlParser.getPreferences());
        SystemWebChromeClient systemWebChromeClient = new SystemWebChromeClient(systemWebViewEngine) {
            @Override
            public void onReceivedTitle(WebView view, String title) {//监听标题改变
                setTitleText(title);
                showBackBar();
            }
        };
        systemWebView.setWebChromeClient(systemWebChromeClient);
        systemWebView.getSettings().setDomStorageEnabled(true);//解决webview白板问题
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            systemWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        handler.postDelayed(runnable, 1000);//每一秒执行一次runnable,作业耗时加一秒.

        mDownLoadInfo = (DownLoadInfo) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_DOWNLOAD_INFO);
        contentId = intent.getIntExtra(IntentFlag.INTENT_FLAG_ID, 0);
        OnlineAnswerFrom = intent.getIntExtra(IntentFlag.INTENT_FLAG_H5_PAGE_TYPE_SOURCE, -1);
        workId = intent.getStringExtra(IntentFlag.INTENT_FLAG_WORK_ID);
        mModule = (Module) getIntent().getSerializableExtra(IntentFlag.INTENT_FLAG_MODULE);
        position = intent.getIntExtra(IntentFlag.INTENT_FLAG_POSITION, 0);
        moduleContent = (ModuleContent) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
        mServiceId = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_SERVICE_ID, -1);
        setValideSource(false);
        ALiYunManager.getInstance().registerListener(aLiYunListener);

        final String saveUUid = CWSys.getSharedString(RepeatKeyUtil.getUuidSaveKey(mDownLoadInfo, mModule, position, workId, 0), null);
        if (null != saveUUid) {
            mUuid = saveUUid;
            Log.d(TAG, "######null != saveUUid######" + saveUUid);
        } else {
            CWSys.setSharedString(RepeatKeyUtil.getUuidSaveKey(mDownLoadInfo, mModule, position, workId, 0), mUuid);
            Log.d(TAG, "######mUuid######" + mUuid);
        }

        startTime = CWSys.getSharedLong(ListenSpeakUtil.getStartTime(mDownLoadInfo, mModule, position, workId, mUuid), 0);
        if (startTime == 0) {
            if (null != mDownLoadInfo) {
                startTime = mDownLoadInfo.getStartTime();
                CWSys.setSharedLong(ListenSpeakUtil.getStartTime(mDownLoadInfo, mModule, position, workId, mUuid), startTime);

            }
        }

        int saveTotalTime = CWSys.getSharedInt(ListenSpeakUtil.getSaveTime(mDownLoadInfo, mModule, position, workId, mUuid), -1);
        if (saveTotalTime != -1) {
            totalTime = saveTotalTime;
        }
    }

    @Override
    protected void loadData() {
        showH5View();
        if (mDownLoadInfo.getType() == CatalogueInfo.PackageMode.PACKAGE_MODE_NEW) {
            mJsonResPath = ESystem.getPackagesJsonPathNew(mDownLoadInfo.getBookId(), mDownLoadInfo.getChapterId(), mDownLoadInfo.getModuleId() + "", mDownLoadInfo.getVersionId());
        } else {
            mJsonResPath = mDownLoadInfo.mJsonResPath;
            //从扫一扫进来，moduleContent不为空
            if (moduleContent != null) {
                mJsonResPath = ESystem.getPackagesJsonPath(moduleContent.getResourceFile());
            }
        }

        if (TextUtils.isEmpty(mJsonResPath)) {
            showToastError("数据加载失败，请清除缓存后重试");
        }
//        start_url = "file://" + ESystem.getOnlinePaperPath() + File.separator + "paper.html";
//        start_url = "http://192.168.18.181/mobile/v1707_haitangban/onlinePaper/paper.html";
        // TODO: 2018/8/27 lzh
        if (DeviceUtil.isPad()) {
//            start_url = "file://" + ESystem.getInteractiveTutorialPath() + File.separator + "paper.html?client=22222";
            start_url = "file://" + ESystem.getInteractiveTutorialPath() + File.separator + "itPaper.html";
        } else {
            start_url = "file://" + ESystem.getInteractiveTutorialPath() + File.separator + "itPaper.html";
        }
        cordovaWebView.loadUrl(start_url);
        Log.e("ActivityPlugin", "execute:action == " + start_url);
        showBackBar();
        checkSubmitFailAnswer();
        checkUnUpLoadPhotos();

    }


    /**
     * 检查未上传成功的图片
     */
    private void checkUnUpLoadPhotos() {
        String onLineAnswerPhotoKye = getOnLineAnswerPhotoKye();
        SerializableManager.getInstance().deSerialize(onLineAnswerPhotoKye, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {

            }

            @Override
            public void failed(Object data) {

            }

            @Override
            public void success(Object data) {
                if (data != null) {
                    List<OnlineAnswerPhotoBean> unUpLoadPhotos = (List<OnlineAnswerPhotoBean>) data;
                    Iterator<OnlineAnswerPhotoBean> iterator = unUpLoadPhotos.iterator();
                    if (iterator.hasNext()) {
                        OnlineAnswerPhotoBean onlineAnswerPhotoBean = iterator.next();
                        if (new File(onlineAnswerPhotoBean.photoPath).exists()) {
                            ALiYunManager.getInstance().add(onlineAnswerPhotoBean.photoPath, onlineAnswerPhotoBean);
                        } else {
                            unUpLoadPhotos.remove(onlineAnswerPhotoBean);
                        }
                    }
                    onlineAnswerPhotoBeans.addAll(unUpLoadPhotos);
                    SerializableManager.getInstance().serialize(getOnLineAnswerPhotoKye(), null);
                }
                super.success(data);
            }
        });
    }


    @Override
    protected void initEvent() {
        EventBus.getDefault().register(this);
        setGoBackListener(new GoBackListener() {
            @Override
            public void goBack() {
                onBackPressed();
            }
        });
        btn_submit_again.setOnClickListener(this);

    }

    public void onEventMainThread(SubmitEvent submitEvent) {
        final String id = submitEvent.getId();
        final String callbackId = submitEvent.getCallbackId();
        if (id.equals("SetTitle")) {
//            setTitle(submitEvent); //标题栏已经由H5提供，app端不用再显示标题
        } else if ("Submit".equals(id)) {
//            提交作业(submitEvent);
        } else if (id.equals("GetOnlineExamination")) {//获取题目内容
            getOnlineExamination(callbackId);
        } else if (id.equals("GetOnlineAnswer")) {//获取用户答案
            getOnlineAnswer(callbackId);
        } else if (id.equals("SetOnlineAnswer")) {//保存答案到本地
            setOnlineAnswer(submitEvent.getJson());
        } else if (id.equals("SubmitOnlineAnswer")) {//提交答案到服务器
            String answerJson = submitEvent.getJson();
            submitOnlineAnswer(callbackId, answerJson, false);
        } else if (id.equals("ExitOnlineAnswer")) {//退出作答界面
            exitOnlineAnswer(submitEvent.getJson());
        } else if (id.equals("GetOnlineKey")) {//
            getOnlineKey(callbackId);
        } else if (id.equals("TakePhoto")) {
            TakePhoto(submitEvent);
        } else if (id.equals("TakePhotoForPad")) {
            TakePhotoForPad(submitEvent);
        } else if (id.equals("IFinishedReading")) {
            String answerJson = submitEvent.getJson();
            submitOnlineAnswer(callbackId, answerJson, true);
        } else if (id.equals("JumpToAppRead")) {
            try {
                String answerJson = submitEvent.getJson();
                JSONObject jsonObject = new JSONObject(answerJson);
                List<SentencesDetail> sentencesDetails = GsonUtil.fromJsonToArrayList(jsonObject.get("sentence_items").toString(), SentencesDetail.class);
                Log.e("TAG", "onEventMainThread = " + GsonUtil.toJson(sentencesDetails));
                int moduleId = 0;
                if (jsonObject.has("moduleId")) {
                    moduleId = jsonObject.getInt("moduleId");
                }
                if (!sentencesDetails.isEmpty()) {
                    EpaperJumpManager.jumpToSentenceNewBook(R.string.go_back, InteractiveTutorialCordovaActivity.this, "0", mDownLoadInfo, jsonObject.get("sentence_items").toString(), moduleId + "", 0, SpeechPlayController.LISTENER_MODE_ZHUJU, 0, 0, "0", 0, null, 0);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }


    private static final int TAKE_PHOTOFORPAD = 4;

    public static final int PHOTO_REQUEST_CAMERA = 3;
    private String mCameraPath;

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PERMISSION_CAMERA:
//                if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
//
//                }
                break;

            default:
                break;
        }
    }

    private void TakePhotoForPad(SubmitEvent submitEvent) {
        try {
            String photoName = new JSONObject(submitEvent.getJson()).getString("fileName");
            mCameraPath = ESystem.getAnswersImagesPath("OnlineAnswerPic") + File.separator + photoName + ".png";
            callbackId = submitEvent.getCallbackId();
            Intent takePhotoForPadIntent = new Intent(this, JournalActivity.class);
            takePhotoForPadIntent.putExtra(JournalActivity.PHOTOPATH, mCameraPath);
            startActivityForResult(takePhotoForPadIntent, TAKE_PHOTOFORPAD);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void TakePhoto(SubmitEvent submitEvent) {
        try {
            String photoName = new JSONObject(submitEvent.getJson()).getString("fileName");
            mCameraPath = ESystem.getAnswersImagesPath("OnlineAnswerPic") + File.separator + photoName + EConstants.CAMERA_DEFAULT_SUFFIX;
            callbackId = submitEvent.getCallbackId();
            boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.CAMERA);
            //调用相机需要动态申请权限。
            if (isHavePermiss) {
                //有权限
                Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                String tempCameraFile = ESystem.getImagesPath(InteractiveTutorialCordovaActivity.this) + File.separator + "temp.jpg";
                Uri fileUri = FileProvider7.getUriForFile(this, new File(tempCameraFile));
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                cameraIntent.putExtra("return-data", true);
                startActivityForResult(cameraIntent, PHOTO_REQUEST_CAMERA);
            } else {
                //无权限
                showgetCameraPermissDialog();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private CWDialog getCameraPermissDialog;

    /**
     * 获取Camera权限提示框
     */
    private boolean showgetCameraPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.CAMERA);
        if (isHavePermiss) {
            useCamera();
        } else {
            if (getCameraPermissDialog == null) {
                getCameraPermissDialog = new CWDialog(this);
                getCameraPermissDialog.setTitle(R.string.get_permiss_title);
                getCameraPermissDialog.setTitleTextColor(Color.BLACK);
                getCameraPermissDialog.setMessage(getString(R.string.get_camera_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getCameraPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getCameraPermissDialog.dismiss();
                        useCamera();
                    }
                });
                getCameraPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getCameraPermissDialog.dismiss();
                    }
                });
            }
            getCameraPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用照相机，判断权限
     */
    private void useCamera() {
        List<String> permissionList_camera = new ArrayList<String>();
        Map<String, String> noteMap_camera = new HashMap<>();
        noteMap_camera.put(Manifest.permission.CAMERA, "相机权限");
        permissionList_camera.add(Manifest.permission.CAMERA);
        if (Build.VERSION.SDK_INT >= 30) {
            permissionList_camera.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            noteMap_camera.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, "读取相册权限");
        }
        XXPermissionTool.checkPermissions(this, //
                permissionList_camera, //
                noteMap_camera, //
                REQUEST_PERMISSION_CAMERA, //
                new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                    @Override
                    public void onCheckPermissionsFinished(int flag) {
                        if (0 == flag) {
                            String tempCameraFile = ESystem.getImagesPath(InteractiveTutorialCordovaActivity.this) + File.separator + "temp.jpg";
                            Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            Uri fileUri = FileProvider7.getUriForFile(InteractiveTutorialCordovaActivity.this, new File(tempCameraFile));
                            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                            cameraIntent.putExtra("return-data", true);
                            startActivityForResult(cameraIntent, PHOTO_REQUEST_CAMERA);
                        }
                    }
                });
    }

    public void onEventMainThread(Answer answer) {
        CWLog.i("作业上传进度", answer.getProgress() + "提交状态" + answer.submitStatus);
    }

    public String getOnLineAnswerKey() {

        String versionId = mDownLoadInfo.getVersionId();
        UserInfoBase userInfo = EApplication.getInstance().getUserInfoBase();
        String userId = "";
        if (null != userInfo) {
            userId = userInfo.getUserId() + "";
        }
        String key = versionId + mDownLoadInfo.getModuleId() + mDownLoadInfo.getChapterId() + workId + OnlineAnswerFrom + userId + EApplication.BRAND_ID;
        return key;
    }

    /**
     * 是否有主观题
     */
    private boolean isSubjective = false;

    /**
     * 提交作业
     *
     * @param callbackId
     * @param answerJson
     */
    private void submitOnlineAnswer(final String callbackId, String answerJson, boolean hasNoAnswers) {

//        this.callbackId = callbackId;
//        this.answerJson = answerJson;
        if (!NetworkUtils.isOnline()) {
            ToastUtil.INSTANCE.toastCenterNoNetError();
            return;
        }

        if (EConstants.IS_YOUKE) {
            NewLoginDialog newLoginDialog = new NewLoginDialog(InteractiveTutorialCordovaActivity.this);
            newLoginDialog.showLoginDialog();
            newLoginDialog.setNewLoginOnClickListener(new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (which == DialogInterface.BUTTON_POSITIVE) {
                        sendCallBackSuccess(callbackId, 1);
                    } else if (which == DialogInterface.BUTTON_NEGATIVE) {
                        sendCallBackSuccess(callbackId, 1);
                    }

                }
            });
        } else {
            try {
                h5AnswersResponse = gson.fromJson(answerJson, H5AnswersResponse.class);

                int remainNum = Integer.parseInt(h5AnswersResponse.remainNum);
                if (remainNum > 0) {
                    String tips = "您还有" + remainNum + "道题目未完成，确定交卷吗？";
                    showConfirmCommitDialog(this, tips, callbackId, answerJson);
                } else {
                    submitAnswer(callbackId, answerJson, hasNoAnswers);

                }
            } catch (Exception e) {
                submitAnswer(callbackId, answerJson, hasNoAnswers);
            }
        }
    }

    private boolean isSubmiting = false;

    private void submitAnswer(final String callbackId, final String answerJson, boolean hasNoAnswers) {

        //先检查图片上传队列还有多少没上传完成。
//        String answerAfter = "";
//        //添加服务ID
//        try {
//            Answer orignalAnswer = gson.fromJson(answerJson, Answer.class);
//            orignalAnswer.setWorkType(mServiceId);
//            answerAfter = gson.toJson(orignalAnswer);
//        }catch (Exception e){
//            answerAfter = answerJson;
//        }

        Log.d(TAG, "#######submitAnswer answerJson#########" + answerJson);
        this.answerJson = answerJson;
        String onLineAnswerKey = RepeatKeyUtil.getOnlineCommitAnswerListKey(mDownLoadInfo, mModule, position, workId, mUuid);
        Log.d(TAG, "###########onLineAnswerKey#########" + onLineAnswerKey);
        SerializableManager.getInstance().serialize(onLineAnswerKey, answerJson);

        ESystem.setSharedString(getOnLineAnswerKey(), callbackId);
        sendCallBackSuccess(callbackId, 1);
        showSubmitView();
        for (OnlineAnswerPhotoBean onlineAnswerPhotoBean : onlineAnswerPhotoBeans) {
            if (TextUtils.isEmpty(onlineAnswerPhotoBean.photoUrl)) {//没有url说明上传还未完成
                Message message = new Message();
                Bundle bundle = new Bundle();
                bundle.putString("callbackId", callbackId);
                bundle.putString("answerJson", answerJson);
                message.setData(bundle);
                ALiYunManager.getInstance().addPic(onlineAnswerPhotoBean.photoPath, onlineAnswerPhotoBean);
                upLoadPicHandler.sendMessageDelayed(message, 2000);
                return;
            }
        }
        final Answer answer = getAnswer(answerJson);
        answer.setStartTime(startTime);
        answer.setWorkType(mServiceId);
        answer.setHasNoAnswers(hasNoAnswers);

        final String saveUUid = CWSys.getSharedString(RepeatKeyUtil.getUuidSaveKey(mDownLoadInfo, mModule, position, workId, 0), null);
        if (saveUUid != null) {
            Log.d(TAG, "#######saveUUid != null##########");
            answer.setSessionId(saveUUid);
        } else {
            Log.d(TAG, "#######saveUUid == null clearRecord() ##########");

            clearRecord();
            finish();
            return;
        }
        final String 最终提交的答案Json = gson.toJson(answer);

        Log.d(TAG, "#######最终提交的答案Json#########" + 最终提交的答案Json);
        showSubmitView();
        EpaperDao.getInstance().submitWork(最终提交的答案Json, 0, answer, new BaseExtCallBack(this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {


            @Override
            public void failed(int errorCode, Object data) {
                CWLog.i("答案提交失败errorCode:" + errorCode, data.toString());
                Log.d(TAG, "#######failed errorCode#########" + errorCode);
                if (null != data) {
                    FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_INTERACTIVE_TUTORIAL, data.toString(), "互动教程提交作业失败：" + getUrl());
                    CWLog.d(TAG, "#######failed errorCode#########" + data.toString());
                }

                if (errorCode != EConstants.ERROR_CODE_REPEAT_COMMIT) {
                    showSubmitFailView();
                } else {
//                    MeJumpManager.jumpToOnlineAnswerResultActivity(OnlineAnswerCordovaActivity.this, OnlineAnswerFrom, totalTime, onlineAnswerSubMitResultBean.doWorkId, answer.workScore, onlineAnswerSubMitResultBean.score, isSubjective, contentId + "");
                    ToastUtil.INSTANCE.toastCenterSuccess("提交成功！");
                    //通知刷新作业列表
                    sendBroadcast(new Intent(EpaperConstant.BROADCAST_HOME_WORK_STATUS_INTERACTIVE_TUTORIAL_FINASH));
                    sendBroadcast(new Intent(EpaperConstant.BROADCAST_AUTONOMIC_STUDY_STATUS_CHANGE_MSG));
                    clearRecord();
                    finish();

                }

            }

            @Override
            public void failed(Object data) {
                if (data != null) {
                    FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_INTERACTIVE_TUTORIAL, data.toString(), "互动教程提交作业失败" + getUrl());
                }

                Log.d(TAG, "#######failed #########" + answerJson);
                CWLog.i("答案提交失败", data.toString());
                showSubmitFailView();
            }

            @Override
            public void success(Object data) {
                sendBroadcast(new Intent(EpaperConstant.BROADCAST_HOME_WORK_STATUS_INTERACTIVE_TUTORIAL_FINASH));
                sendBroadcast(new Intent(EpaperConstant.BROADCAST_AUTONOMIC_STUDY_STATUS_CHANGE_MSG));
                OnlineAnswerSubMitResultBean onlineAnswerSubMitResultBean = (OnlineAnswerSubMitResultBean) data;
                isSubjective = onlineAnswerSubMitResultBean.isHasNoCorrect();
                answer.actualScore = onlineAnswerSubMitResultBean.getScore();
                doWorkId = onlineAnswerSubMitResultBean.getDoWorkId();
                returnWorkTime = onlineAnswerSubMitResultBean.getWorkLong();
                clearRecord();

                if (isjumpToResult) { //如果当前activity还在前台就跳转。
//                    MeJumpManager.jumpToOnlineAnswerResultActivity(InteractiveTutorialCordovaActivity.this, OnlineAnswerFrom, totalTime, onlineAnswerSubMitResultBean.doWorkId, answer.workScore, onlineAnswerSubMitResultBean.score, isSubjective, contentId + "",mDownLoadInfo);
                    //此处就是为了判断是否是考试用书
                    boolean orNotWatchDetails = CheckIsExamForDetail.INSTANCE.isOrNotWatchDetails(InteractiveTutorialCordovaActivity.this, contentId + "", -1);
                    if (!answer.getWorkId().equals("0") && !orNotWatchDetails) {//作业进来,并且是考试用书
                        handleHomeworkIn();
                    } else {
                        jumpToInteractveCheckDetail(doWorkId);
                        finish();
                    }
                }
                isSubmiting = false;
            }
        });
    }

    private void handleHomeworkIn() {
        mBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent == null) {
                    return;
                }
                if (EpaperConstant.BROADCAST_INTERACTIVE_TUTORIAL_ADD_POINT_OVER.equals(intent.getAction())) {
                    commitSuccessForToastView();
                    //删除了本地package ，刷新状态
                    //此处就是为了弹提示
                    boolean orNotWatchDetails = CheckIsExamForDetail.INSTANCE.isOrNotWatchDetails(InteractiveTutorialCordovaActivity.this, contentId + "", 1);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            finish();
                        }
                    }, 4 * 1000);
                }
            }
        };
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(EpaperConstant.BROADCAST_INTERACTIVE_TUTORIAL_ADD_POINT_OVER);
        mContext.registerReceiver(mBroadcastReceiver, myIntentFilter);
    }


    private boolean isjumpToResult = true;

    private void checkSubmitFailAnswer() {
//        String readKey=getOnLineAnswerKey();

        String onLineAnswerKey = RepeatKeyUtil.getOnlineCommitAnswerListKey(mDownLoadInfo, mModule, position, workId, mUuid);

        SerializableManager.getInstance().deSerialize(onLineAnswerKey, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {

            }

            @Override
            public void failed(Object data) {

            }

            @Override
            public void success(Object data) {
                if (data != null) {
                    InteractiveTutorialCordovaActivity.this.answerJson = String.valueOf(data);

                    Log.e(TAG, "#######this.answerJson answer###########" + answerJson);
                    callbackId = ESystem.getSharedString(getOnLineAnswerKey());
                    if (!TextUtils.isEmpty(answerJson) && !TextUtils.isEmpty(callbackId)) {
                        showSubmitFailView();
                    }
                }
            }
        });
    }

    private void exitOnlineAnswer(String answerJson) {

        String onLineAnswerKey = RepeatKeyUtil.getOnlineAnswerListKey(mDownLoadInfo, mModule, position, workId, mUuid);
        String onLineAnswerPhotoKye = getOnLineAnswerPhotoKye();
        Log.d(TAG, "##########exitOnlineAnswer answerJson#########" + answerJson);
        Log.d(TAG, "#####BaseRequestUtil.getInstance().cancelAll#####" + workId);
        BaseRequestUtil.getInstance().cancelAll(workId);
        String saveTimeKey = ListenSpeakUtil.getSaveTime(mDownLoadInfo, mModule, position, workId, mUuid);
        DialogUtil.showConfirmEndOnlineAnswerDialog(InteractiveTutorialCordovaActivity.this, answerJson, onLineAnswerKey, isSubmiting, onLineAnswerPhotoKye, onlineAnswerPhotoBeans, saveTimeKey, totalTime);

    }

    private String getOnLineAnswerPhotoKye() {
        return getOnLineAnswerKey() + "photo";

    }

    private Answer getAnswer(String H5传来的answerJson) {

        tempAnswer = new Answer();
        tempAnswer.setContentId(contentId);
        tempAnswer.setDoWorkPackageUrl("");
        EApplication application = (EApplication) getBaseApplication();
        Clazz clazz = application.getClazz();
        userInfo = application.getUserInfoBase();
        if (null != userInfo && null != H5传来的answerJson) {
            if (TextUtils.isEmpty(workId)) {
                workId = "0";
            }
            tempAnswer.setWorkId(workId);
            tempAnswer.setWorkLong(totalTime);
            if (clazz == null) {
                classId = "0";
            } else {
                classId = clazz.getClassId() + "";
            }
            tempAnswer.setClassId(classId);
            tempAnswer.setUserName(userInfo.getRealName());

            if (null != h5AnswersResponse) {
                tempAnswer.remainNum = h5AnswersResponse.remainNum;
            }

            try {
                JSONObject jsonObject = new JSONObject(H5传来的answerJson);

                tempAnswer.setWorkAnswers(jsonObject.getString("answers"));
                JSONObject resultJsonObject = new JSONObject(result);
                String ref_score = "0";
                try {
                    ref_score = resultJsonObject.getString("total_score");
                } catch (Exception e) {

                }

                tempAnswer.setWorkScore(Float.parseFloat(ref_score));
            } catch (Exception e) {
                tempAnswer.setWorkAnswers("[]");
            }
            tempAnswer.setJsonVersion(EConstants.JSON_VERSION);
            tempAnswer.setUserAnswer(ESystem.USER_ANSWER);
            tempAnswer.setCreateTime(System.currentTimeMillis());
            tempAnswer.setBrandId(EApplication.BRAND_ID);
            int moduleId;

            if (moduleContent != null) {
                moduleId = mModule.getModuleInfo().getModuleId();
                tempAnswer.setResourceName(moduleContent.getResourceName());
                tempAnswer.setVersionId(moduleContent.getVersionId());
                tempAnswer.setParentVersionId(moduleContent.getParentVersionId());
                tempAnswer.setModuleId(moduleId);
                tempAnswer.setResourceType(moduleContent.getResourceType());
                //
                mDownLoadInfo.setVersionId(moduleContent.getVersionId());
                mDownLoadInfo.setResourceType(moduleContent.getResourceType());
                mDownLoadInfo.setModuleId(moduleId + "");
                mDownLoadInfo.setResourceName(moduleContent.getResourceName());


            } else {
                if (mDownLoadInfo != null) {
                    moduleId = Integer.parseInt(mDownLoadInfo.getModuleId());
                    tempAnswer.setResourceName(mDownLoadInfo.getResourceName());
                    tempAnswer.setResourceType(mDownLoadInfo.getResourceType());
                    tempAnswer.setVersionId(mDownLoadInfo.getVersionId());
                    tempAnswer.setModuleId(moduleId);
                }
            }
            if (mDownLoadInfo != null) {
                tempAnswer.setPackageId(mDownLoadInfo.getBookId());
                tempAnswer.setcId(mDownLoadInfo.getChapterId());
            }


        }
        return tempAnswer;
    }

    /**
     * 设置用户已经作答的答案
     */
    private void setOnlineAnswer(String answer) {

        String onLineAnswerKey = RepeatKeyUtil.getOnlineAnswerListKey(mDownLoadInfo, mModule, position, workId, mUuid);
        CWLog.d(TAG, "#######setOnlineAnswer answer###########" + answer);
        SerializableManager.getInstance().serialize(onLineAnswerKey, answer);
    }

    private void getOnlineAnswer(final String callbackId) {
        CWLog.d(TAG, "#######getOnlineAnswer #########" + callbackId);
        SerializableManager.getInstance().deSerialize(RepeatKeyUtil.getOnlineAnswerListKey(mDownLoadInfo, mModule, position, workId, mUuid), new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                sendCallBackSuccess(callbackId, "");
            }

            @Override
            public void failed(Object data) {
                sendCallBackSuccess(callbackId, "");
            }

            @Override
            public void success(Object data) {
                String onlineAnswer = data.toString();
                Log.d(TAG, "#######getOnlineAnswer onlineAnswer#########" + onlineAnswer);

                if (EConstants.IS_YOUKE) {
                    sendCallBackSuccess(callbackId, "");
                } else {
                    sendCallBackSuccess(callbackId, data.toString());
                }

            }
        });
    }

    private void getOnlineKey(String callbackId) {
        String onLineAnswerKey = getOnLineAnswerKey();
        sendCallBackSuccess(callbackId, onLineAnswerKey);
    }

    public String start_url = "";


    /**
     * 做作业耗时
     */
    private int totalTime = 0;
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            totalTime++;
            handler.postDelayed(this, 1000);
        }
    };
    private Handler upLoadPicHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            String callbackId = bundle.getString("callbackId");
            String answerJson = bundle.getString("answerJson");
            submitAnswer(callbackId, answerJson, false);
            return true;
        }
    });

    @Override
    public void onLoadOver() {
        hideTitleBar();
    }

    @Override
    public void onBackFinish() {

    }

    @SuppressLint("NewApi")
    @Override
    public void onBackPressed() {
        try {

            systemWebView.evaluateJavascript("local.getAnswer()", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String answer) {
                    CWLog.i("从JS获取的答案：", answer);
                    exitOnlineAnswer(answer);
                }
            });

        } catch (NoSuchMethodError error) {

        }

    }


    public final ArrayBlockingQueue<String> onPageFinishedUrl = new ArrayBlockingQueue<String>(5);
    protected CordovaInterfaceImpl cordovaInterface = new CordovaInterfaceImpl(this) {
        @Override
        public Object onMessage(String id, Object data) {
            if ("onPageFinished".equals(id)) {
                try {
                    onPageFinishedUrl.add((String) data);
                } catch (IllegalStateException e) {
                }
            }
            return super.onMessage(id, data);
        }
    };

    private void showH5View() {
        isSubmiting = false;
        systemWebView.setVisibility(View.VISIBLE);
        hideTitleBar();
        ll_submiting.setVisibility(View.GONE);
        rel_submit_fail.setVisibility(View.GONE);
    }

    private void showSubmitView() {
        isSubmiting = true;
        showTitleBar();
        systemWebView.setVisibility(View.GONE);
        ll_submiting.setVisibility(View.VISIBLE);
        rel_submit_fail.setVisibility(View.GONE);
    }

    private void showSubmitFailView() {
        isSubmiting = true;
        hideTitleBar();
        systemWebView.setVisibility(View.GONE);
        ll_submiting.setVisibility(View.GONE);
        rel_submit_fail.setVisibility(View.VISIBLE);
    }

    private void commitSuccessForToastView() {
        isSubmiting = true;
        showTitleBar();
        systemWebView.setVisibility(View.GONE);
        ll_submiting.setVisibility(View.GONE);
        rel_submit_fail.setVisibility(View.GONE);
    }


    /**
     * 获取在线作答资源
     *
     * @param callbackId
     */
    private void getOnlineExamination(final String callbackId) {
        EpaperDao.getInstance().getResource(mJsonResPath, new BaseExtCallBack(this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void success(final Object data) {
                result = data.toString();
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (OnlineAnswerFrom == FROM_HOME_WORK) {//来自作业
                        jsonObject.put("isWork", 1);
                    } else {
                        jsonObject.put("isWork", 0);//来自书桌
                    }
                    sendCallBackSuccess(callbackId, jsonObject.toString());
                } catch (JSONException e) {
                    sendCallBackSuccess(callbackId, result);
                    e.printStackTrace();
                }
            }

            @Override
            public void failed(int errorCode, Object data) {
                sendCallBackSuccess(callbackId, data.toString());

                FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_INTERACTIVE_TUTORIAL, "文件不存在==" + mJsonResPath, mDownLoadInfo.getBookName() + " :" + mDownLoadInfo.getChapterName() + " :" + mDownLoadInfo.getUrl());
                ToastUtil.INSTANCE.toastCenterError("文件不存在，请清除缓存后重试");
                finish();
                super.failed(errorCode, data);
            }

            @Override
            public void failed(Object data) {
                sendCallBackSuccess(callbackId, "");
                FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_INTERACTIVE_TUTORIAL, "文件不存在==" + mJsonResPath, mDownLoadInfo.getBookName() + " :" + mDownLoadInfo.getChapterName() + " :" + mDownLoadInfo.getUrl());
                ToastUtil.INSTANCE.toastCenterError("文件不存在，请清除缓存后重试");
                finish();
            }
        });
    }

    private void sendCallBackFail(String callbackId, String error) {
        CallbackContext callbackContext = new CallbackContext(callbackId, cordovaWebView);
        callbackContext.error(error);
    }

    private void sendCallBackSuccess(String callbackId, String result) {
        CallbackContext callbackContext = new CallbackContext(callbackId, cordovaWebView);
        callbackContext.success(result);
    }

    private void sendCallBackSuccess(String callbackId, JSONObject result) {
        CallbackContext callbackContext = new CallbackContext(callbackId, cordovaWebView);
        callbackContext.success(result);
    }

    private void sendCallBackSuccess(String callbackId, int result) {
        CallbackContext callbackContext = new CallbackContext(callbackId, cordovaWebView);
        callbackContext.success(result);
    }

    public CordovaWebView getCordovaWebView() {
        return cordovaWebView;
    }

    @Override
    protected void onDestroy() {
        ALiYunManager.getInstance().unRegisterListener(aLiYunListener);
        isjumpToResult = false;
        EventBus.getDefault().unregister(this);
        if (mBroadcastReceiver != null)
            unregisterReceiver(mBroadcastReceiver);


        if (systemWebView != null)
            systemWebView.destroy();
        if (cordovaWebView != null)
            cordovaWebView.getEngine().destroy();
        if (cordovaWebView != null)
            cordovaWebView.getPluginManager().onDestroy();
        super.onDestroy();
    }


    @Override
    public void finish() {
        isCancelToastOnPause = false;
        isjumpToResult = false;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ViewGroup view = (ViewGroup) getWindow().getDecorView();
                view.setBackgroundColor(getResources().getColor(R.color.white));
                for (int i = 0; i < view.getChildCount(); i++) {
                    if (view.getChildAt(i).getParent() != null) {
                        view.removeView(view.getChildAt(i));
                    }
                }
                InteractiveTutorialCordovaActivity.super.finish();
            }
        });
    }

    /**
     * 未完成作业提交提醒窗口
     */
    public void showConfirmCommitDialog(final Activity context, final String tips, final String callbackId, final String answerJson) {
        CWDialog dialog = new CWDialog(context);
        dialog.setMessage(tips);
        dialog.setPositiveButton(android.R.string.cancel, null)
                .setNegativeButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();
                                submitAnswer(callbackId, answerJson, false);

                            }
                        })
                .show();
    }

    private ALiYunManager.ALiYunListener aLiYunListener = new ALiYunManager.ALiYunListener() {
        @Override
        public void onProgress(Object tag, long currentSize, long totalSize) {

        }

        @Override
        public void onSuccess(Object tag, String url) {
            try {
                OnlineAnswerPhotoBean onlineAnswerPhotoBean = (OnlineAnswerPhotoBean) tag;
                for (OnlineAnswerPhotoBean answerPhotoBean : onlineAnswerPhotoBeans) {
                    if (answerPhotoBean.photoPath.equals(onlineAnswerPhotoBean.photoPath)) {
                        answerPhotoBean.photoUrl = url;
//                        onlineAnswerPhotoBeans.remove(answerPhotoBean);
                    }
                }
            } catch (Exception e) {
                showToastError("图片上传失败，请重试");
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Object tag, int errorCode) {
            if (tag != null) {
//                OnlineAnswerPhotoBean onlineAnswerPhotoBean = (OnlineAnswerPhotoBean) tag;
//                ALiYunManager.getInstance().addPic(onlineAnswerPhotoBean.photoPath, onlineAnswerPhotoBean);
            }
            ToastUtil.INSTANCE.toastCenterError(errorCode + "图片上传失败，重试中..");
        }
    };

    @Override
    protected void onResume() {
        isjumpToResult = true;
        super.onResume();
    }

    @Override
    protected void onPause() {
        isjumpToResult = false;
        super.onPause();
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.btn_submit_again) {//重新提交
            if (!NetworkUtils.isOnline()) {
                ToastUtil.INSTANCE.toastCenterNoNetError();
                return;
            }
            Log.d(TAG, "######onClick answerJson#########" + answerJson);

            submitAnswer(callbackId, answerJson, false);
        }
    }

    public static boolean isPad(Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    private List<OnlineAnswerPhotoBean> onlineAnswerPhotoBeans = new ArrayList<OnlineAnswerPhotoBean>();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {
            if (requestCode == NewLoginActivity.FOR_LOGIN) {//顶号后重新登录成功
                finish();

            } else if (requestCode == PHOTO_REQUEST_CAMERA) {//拍照答题
                try {
                    String tempCameraFile = ESystem.getImagesPath(InteractiveTutorialCordovaActivity.this) + File.separator + "temp.jpg";
                    String outputPath = FileUtil.compressImage(tempCameraFile, mCameraPath, 100);
                    OnlineAnswerPhotoBean onlineAnswerPhotoBean = new OnlineAnswerPhotoBean();
                    onlineAnswerPhotoBean.photoPath = outputPath;
                    onlineAnswerPhotoBean.callbackId = callbackId;
                    ALiYunManager.getInstance().addPic(outputPath, onlineAnswerPhotoBean);
                    String photoUrlKey = ALiYunManager.getInstance().getPicKey(outputPath);
                    String photoUrl = ALiYunManager.ACCESS_URL + photoUrlKey;
//                    onlineAnswerPhotoBean.photoUrl = photoUrl;
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("photoPath", outputPath);
                    jsonObject.put("photoUrl", photoUrl);
                    onlineAnswerPhotoBeans.add(onlineAnswerPhotoBean);
                    sendCallBackSuccess(onlineAnswerPhotoBean.callbackId, jsonObject);
                } catch (Exception e) {
                    showToastError("获取图片失败，请重新拍照上传");
                    CWLog.e("获取图片失败", "获取图片失败");
                    e.printStackTrace();
                }
            } else if (requestCode == TAKE_PHOTOFORPAD) {
                try {
                    OnlineAnswerPhotoBean onlineAnswerPhotoBean = new OnlineAnswerPhotoBean();
                    String photoUrlKey = ALiYunManager.getInstance().getPicKey(mCameraPath);
                    String photoUrl = ALiYunManager.ACCESS_URL + photoUrlKey;
                    onlineAnswerPhotoBean.photoPath = mCameraPath;
                    onlineAnswerPhotoBean.callbackId = callbackId;
                    ALiYunManager.getInstance().addPic(mCameraPath, onlineAnswerPhotoBean);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("photoPath", mCameraPath);
                    jsonObject.put("photoUrl", photoUrl);
                    onlineAnswerPhotoBeans.add(onlineAnswerPhotoBean);
                    sendCallBackSuccess(onlineAnswerPhotoBean.callbackId, jsonObject);
                } catch (Exception e) {
                    showToastError("获取图片失败，请重新拍照上传");
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 清除记录
     */
    private void clearRecord() {
//        清除本次做作业或自主练习活动key,只有活动key 清
        Log.d(TAG, "#######clearRecord #########");
        CWSys.setSharedString(RepeatKeyUtil.getUuidSaveKey(mDownLoadInfo, mModule, position, workId, 0), null);
        SerializableManager.getInstance().serialize(getOnLineAnswerKey(), null);
        ESystem.setSharedString(getOnLineAnswerKey(), null);
        //提交成功 清除保存的开始时间
        CWSys.setSharedLong(ListenSpeakUtil.getStartTime(mDownLoadInfo, mModule, position, workId, mUuid), 0);
    }

    private void jumpToInteractveCheckDetail(String doWorkId) {
        //http://prevm.teacher.jiaofuyun.com/v1706_moliban/onlinePaper/detail.html#clientId=20001&userId=543885408&brandId=524726977&versionId=634828917904331620&doWorkId=7217678200179671
        String clientId = EConstants.CLIENT_ID;
        String userId = EApplication.getInstance().getUserInfoBase().getUserId() + "";
        String brandId = EApplication.BRAND_ID + "";
        String versionId = mDownLoadInfo.getVersionId();
        String title;
        try {
            title = java.net.URLEncoder.encode(mDownLoadInfo.getResourceName(), "UTF-8");
        } catch (Exception e) {
            title = "";
        }
        title = title.replace("+", "%20");
        String url = EpaperConstant.URL_INTERACTIVE_TUTORIAL_DETAIL_H5 + "clientId=" + clientId + "&userId=" + userId + "&brandId=" + brandId + "&versionId=" + versionId
                + "&doWorkId=" + doWorkId + "&pageType=1" + "&packageId=" + mDownLoadInfo.getBookId() + "&cId=" + mDownLoadInfo.getChapterId() + "&title=" + title;
        MeJumpManager.jumpToStudyRecordH5Activity(-1, this, R.string.go_back, -1, url, mDownLoadInfo.getResourceName(), 0);
    }
}
